package indi.jp.project.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import indi.jp.project.center.entity.MsgEnum;
import indi.jp.project.wechat.entity.WeappMsg;
import indi.jp.project.wechat.service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信服务
 *
 * @author jiangping
 * @date 2022/3/2
 */
@Service
public class WechatServiceImpl implements WechatService {

    public static String APP_ID = "wxe8e24671c9885533";

    public static String APP_SECRET = "4c8d1a527997b86b7ef7d298753e7278";

    public static String ACCESS_TOKEN = "";

    // 设定access_token超时时间为一个半小时，防止出现已过期仍然调用的情况
    public static long EXPIRED_IN = 5400L;

    public static long EXPIRED_TIMESTAMP = 0L;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String getOpenid(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }
        String json = restTemplate.getForObject(url, String.class);
        JSONObject jo = JSONObject.parseObject(json);
        return jo.get("openid").toString();
    }

    @Override
    public void send(WeappMsg weappMsg) {
        long timestamp = new Date().getTime();
        System.out.println(timestamp);
        if (timestamp > EXPIRED_TIMESTAMP || "".equals(ACCESS_TOKEN)) {
            ACCESS_TOKEN = getAccessToken();
            EXPIRED_TIMESTAMP = timestamp + EXPIRED_IN * 1000;
        }
        System.out.println(ACCESS_TOKEN);
        System.out.println(EXPIRED_TIMESTAMP);
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + ACCESS_TOKEN;
        weappMsg.setAccess_token(ACCESS_TOKEN);
        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }

        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, weappMsg, String.class);
        System.out.println("==========================================");
        System.out.println(responseEntity.getBody());
    }

    /**
     * 获取access_token
     */
    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + APP_ID + "&secret=" + APP_SECRET;
        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }
        String json = restTemplate.getForObject(url, String.class);
        JSONObject jo = JSONObject.parseObject(json);
        return jo.get("access_token").toString();
    }

    /**
     * 待通知消息
     *
     * @return
     */
    public static Map<String, Map<String, String>> createReviewMsg() {
        Map<String, Map<String, String>> map = new HashMap<>();
        Map<String, String> a = new HashMap<>();
        a.put("value", "444");
        map.put("thing4", a);
        Map<String, String> b = new HashMap<>();
        b.put("value", "2022年3月2日 15:01");
        map.put("time6", b);
        Map<String, String> c = new HashMap<>();
        c.put("value", "888");
        map.put("thing8", c);
        Map<String, String> d = new HashMap<>();
        d.put("value", "444");
        map.put("thing2", d);
        return map;
    }

    public static void main(String[] args) {
        WeappMsg weappMsg = new WeappMsg();
        WechatServiceImpl wechatService = new WechatServiceImpl();
        String openid = "oiLJU5RiBTKQwRc6L6K-V6NtnJVo";
        weappMsg.setTouser(openid);
        weappMsg.setTemplate_id(MsgEnum.REVIEW.getTemplateId());
        weappMsg.setPage("/page/index/index");
        weappMsg.setData(createReviewMsg());
        weappMsg.setMiniprogram_state("developer");
        wechatService.send(weappMsg);

    }

}
